package com.huabo.monitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.JsonBean;
import com.huabo.monitor.entity.*;
import com.huabo.monitor.service.*;
import com.huabo.monitor.util.ConstClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author：yhr
 * @date:2022-09-13 13:42
 * @description:
 */
@RestController
@Slf4j
@Api(value = "内控测试-测试任务", tags = {"内控测试-测试任务所有接口"})
@RequestMapping(value = "/nbkz")
public class CsrwController {


    @Resource
    ITblTestplanService testplanService;
    @Autowired
    ITblStaffService iTblStaffService;


    @Autowired
    TblAssessService tblAssessService;

    @Resource
    CsfaService csfaService;

    @Resource
    ITblTestelementService iTblTestelementService;
    @Resource
    CsrwService csrwService;

    @Resource
    ITblTesttaskService  testtaskService;

    @Resource
    ITblAttachmentService   attachmentService;
    @Resource
    ITblTesttaskAttService   testtaskAttService;
    /**
     * 测试任务
     *
     * @param
     * @return
     */
    @GetMapping(value = "/nkcs/impl/control_test_impl_list")
    @ResponseBody
    @ApiOperation("测试任务-主页")
    public JsonBean nkcs_control_test_impl_list(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        // TblStaff user = (TblStaff) request.getSession().getAttribute("longUser");
        //TblOrganization attribute = (TblOrganization) request.getSession().getAttribute("hbOrgEntity");// 选则的机构
        // pageBean = service.findAllRw(null, pageNumber,
        // pageBean.getPageSize(), "", "",user.getStaffid().toString());
        // 查看测试任务
        IPage<TblTestplan> iPage;
        iPage = csrwService.findAllRwToOrg(pageNumber,
                user.getStaffid().toString(), user.getCurrentOrg().getOrgid().toString());

        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("pageBean", iPage);

        return new JsonBean(200, "success", mv);

    }


    @GetMapping(value = "/csrw/gettree")
    @ResponseBody
    @ApiOperation("测试任务-左侧树")
    public JsonBean csrw_getTree(
            @ApiParam(name = "planid", value = "planid") @RequestParam(value = "planid", required = false) String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("panid",planid);
                mv.put("templId",plan.getTesttemid());
                if (StringUtils.isNotBlank(planid)) {
                    TblTestplan testplan = this.testplanService.getById(new BigDecimal(planid));
                    if (testplan != null && testplan.getReturnstatus() != null && testplan.getReturnstatus().toString().equals("1")) {
                        //TblStaff user = (TblStaff) request.getSession().getAttribute("longUser");
                        List<Tree> tree = this.csrwService.getTreeCSRWByChildsReturn(plan.getTesttemid().toString(), user.getStaffid().toString(), planid);
                        if (tree != null && tree.size() > 0) {
                            mv.put("tree",tree);
                            return new JsonBean(200, "success", mv);
                        } else {
                            tree = this.csrwService.getTreeCSRWByChilds(plan.getTesttemid().toString(), user.getStaffid().toString(), planid);
                            mv.put("tree",tree);
                            return new JsonBean(200, "success", mv);
                        }
                    } else {

                        List<Tree>     tree = this.csrwService.getTreeCSRWByChilds(plan.getTesttemid().toString(), user.getStaffid().toString(), planid);
                        mv.put("tree",tree);
                        return new JsonBean(200, "success", mv);
                    }
                }


            }
        }
        return new JsonBean(-1, "planid不存在", planid);
    }




    @GetMapping(value = "/csrw/def_list")
    @ResponseBody
    @ApiOperation("测试任务-右侧列表")
    public JsonBean csrw_gzdg_def_list(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "node",defaultValue = "780809") @RequestParam(value = "node", required = false) String node,
            @ApiParam(name = "templId", value = "templId",defaultValue = "780808") @RequestParam(value = "templId", required = false)String templId,
            @ApiParam(name = "planid", value = "planid",defaultValue = "790436") @RequestParam(value = "planid", required = false)String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        Map<String, Object> mv = new LinkedHashMap<>();
        IPage<Map<String,Object>> pageBean=new Page<>(pageNumber,ConstClass.DEFAULT_SIZE);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan testplan = this.testplanService.getById(new BigDecimal(planid));
            if (testplan != null && testplan.getReturnstatus() != null && testplan.getReturnstatus().toString().equals("1")) {

                pageBean = this.csrwService.fingByTreeCSRWByUserReturn(node, templId, planid, user.getStaffid(), pageNumber);

                mv.put("pageBean", pageBean);
                mv.put("str", "1");
            } else {

                pageBean = this.csrwService.fingByTreeCSRWByUser(node, templId, planid, user.getStaffid(), pageNumber);
                mv.put("pageBean", pageBean);
                //mv.addObject("str", "1");
            }
            mv.put("plan", testplan);
        }

        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);

        return new JsonBean(200, "success", mv);

    }



    @GetMapping(value = "/csmb/elemendatail")
    @ResponseBody
    @ApiOperation("测试任务-右侧列表-点击编号查看详情")
    public JsonBean elemendatail(
            @ApiParam(name = "elementId", value = "elementId",defaultValue = "780810") @RequestParam(value = "elementId", required = false) BigDecimal elementId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        if (null != elementId) {
            TblTestelement element = this.iTblTestelementService.getById(elementId);

            mv.put("element", element);
        }

        return new JsonBean(200, "success", mv);
    }



    @GetMapping(value = "/csrw/addtask")
    @ResponseBody
    @ApiOperation("测试任务-右侧列表-点击修改/测试查询")
    public JsonBean addtask(
            @ApiParam(name = "ementid", value = "ementid",defaultValue = "780810") @RequestParam(value = "ementid") BigDecimal ementid,
            @ApiParam(name = "planid", value = "planid",defaultValue = "790436") @RequestParam(value = "planid")BigDecimal planid,
            @ApiParam(name = "node", value = "node",defaultValue = "780809") @RequestParam(value = "node", required = false) String node,
            @ApiParam(name = "templId", value = "templId",defaultValue = "780808") @RequestParam(value = "templId", required = false)String templId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        if (ementid != null && planid != null) {
            QueryWrapper<TblTesttask> qw=new  QueryWrapper<>();
            qw.eq("elementid",ementid).eq("planid",planid);


            TblTesttask task = this.testtaskService.getOne(qw);
            TblTestelement element = this.iTblTestelementService.getById(ementid);
            List<TblAttachment> atts = attachmentService.findtTblAttachmentByTask(task.getTesttaskid());
            mv.put("element", element);
            mv.put("task", task);
            mv.put("atts", atts);
        }

        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);


        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试任务-修改/测试页面-附件保存")
    @PostMapping(value = "/csrw/control_test_impl_upload")
    public JsonBean control_test_impl_upload(

            @ApiParam(name = "projectid", value = "testtaskid",defaultValue = "") @RequestParam(value = "projectid")String projectid,
            @ApiParam(name="file",value="附件上传entity",required=true) MultipartFile file,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        String fileName = file.getOriginalFilename();
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        String oldname = fileName.substring(0, fileName.lastIndexOf("."));
        String newname = fileName.replace(oldname, "00"+timeInMillis + "csrw");
        long size = file.getSize();
        try {
            boolean flag = FtpUtil.uploadFile(newname, file.getInputStream());
            if (flag) {
                log.info("上传成功");
            } else {
                log.info("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        TblAttachment a = new TblAttachment();
        a.setAttname(fileName);
//        a.set
//        TblTesttask task = new TblTesttask();
//        task.setTesttaskid(new BigDecimal(projectid));
//        a.getTblTesttasks().add(task);
        a.setAttpath(newname);
        a.setAttsize(new BigDecimal(size / 1024));
        a.setUploader(user.getUsername());
        a.setUploadtime(LocalDateTime.now());
        attachmentService.save(a);

        TblTesttaskAtt tblTesttaskAtt=new TblTesttaskAtt();
        tblTesttaskAtt.setAttid(a.getAttid());
        tblTesttaskAtt.setTesttaskid(new BigDecimal(projectid));
        testtaskAttService.save(tblTesttaskAtt);
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("att",a);
        mv.put("taskAtt",tblTesttaskAtt);
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试任务-修改/测试页面-附件删除")
    @PostMapping(value = "/csrw/control_test_impl_upload_del")
    public JsonBean control_test_impl_upload_del(
            @ApiParam(name = "attid", value = "attid") @RequestParam(value = "attid")BigDecimal attid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        if (attid != null ) {
            attachmentService.deleteAttAndTaskAtt(attid);
        }
        return new JsonBean(200, "success", null);
    }



    /**
     * 测试任务-保存测试信息
     *
     * @param
     * @return
     */
    @ApiOperation("测试任务-修改/测试页面-保存测试")
    @PostMapping(value = "/csrw/control_test_impl_save")
    public JsonBean nkcs_control_test_impl_save(
            @ApiParam(name = "testtaskid", value = "testtaskid") @RequestParam(value = "testtaskid",required = false) String testtaskid,
            @ApiParam(name = "memo", value = "备注") @RequestParam(value = "memo",required = false) String memo,
            @ApiParam(name = "procedures", value = "测试程序") @RequestParam(value = "procedures",required = false) String procedures,
            @ApiParam(name = "testresult", value = "测试结果") @RequestParam(value = "testresult",required = false) String testresult,
            @ApiParam(name = "testpointvalidity", value = "测试有效性value=1or2or3") @RequestParam(value = "testpointvalidity",required = false)String testpointvalidity,
            @ApiParam(name = "planid", value = "planid") @RequestParam(value = "planid",required = false)  BigDecimal planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        Integer result = 0;
        TblTesttask newtask =new TblTesttask();
        if (StringUtils.isNotBlank(testtaskid)) {
            newtask = this.testtaskService.getById(testtaskid);
            newtask.setTestpointvalidity(testpointvalidity);
            newtask.setMemo(memo);
            newtask.setProcedures(procedures);
            newtask.setTestresult(testresult);
            newtask.setTeststatus("已完成");
            testtaskService.updateById(newtask);
            mv.put("testtask",newtask);
            result = 1;
        } else {
            // 业务不熟 注释掉
//            result = 1;
//            newtask.setTestpointvalidity(testpointvalidity);
//            newtask.setMemo(memo);
//            newtask.setProcedures(procedures);
//            newtask.setTestresult(testresult);
//            //newtask.setTeststatus("已完成");
//            testtaskService.save(newtask);
        }
        if (planid != null) {
            TblTestplan plan = testplanService.getById(planid);
            plan.setPlanstatus("执行中");
            testplanService.updateById(plan);
            mv.put("plan",plan);
        }

        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试任务-全部提交")
    @PostMapping(value = "/csrw/saveall", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String saveall(
            @ApiParam(name = "planid", value = "planid") @RequestParam(value = "planid",required = false)  String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return JsonBean.error("token错误或已过期");
        }
        if (StringUtils.isNotBlank(planid)) {
            TblStaffUtil user = DealUserToken.parseUserToken(token);
            return this.csrwService.saveAll(new BigDecimal(planid),user.getStaffid());
        }
        return JsonBean.error("保存失败");
    }



}
